import { defineStore } from 'pinia'
import { http } from '../utils/http'
import { ElMessage } from 'element-plus'

export const useUserStore = defineStore('user', {
  state: () => ({
    token: localStorage.getItem('token'),
    user: JSON.parse(localStorage.getItem('user') || 'null')
  }),

  getters: {
    isAuthenticated: (state) => !!state.token
  },

  actions: {
    async login(email, password) {
      try {
        const response = await http.post('/users/login', { email, password })
        const { token, user } = response
        if (!token) throw new Error('登录失败：未收到token')

        this.token = token
        localStorage.setItem('token', token)
        this.user = user
        localStorage.setItem('user', JSON.stringify(user))
        ElMessage.success('登录成功')
      } catch (error) {
        console.error('Login error:', error)
        const errorMessage = error.response?.data?.message || '登录失败'
        ElMessage.error(errorMessage)
        throw error
      }
    },

    async register(username, email, password) {
      try {
        const response = await http.post('/users/register', { username, email, password })
        const { token, user } = response
        if (!token) throw new Error('注册失败：未收到token')

        this.token = token
        localStorage.setItem('token', token)
        this.user = user
        localStorage.setItem('user', JSON.stringify(user))
        ElMessage.success('注册成功')
      } catch (error) {
        console.error('Register error:', error)
        const errorMessage = error.response?.data?.message || '注册失败'
        ElMessage.error(errorMessage)
        throw error
      }
    },

    async logout() {
      this.token = null
      this.user = null
      localStorage.removeItem('token')
      localStorage.removeItem('user')
      ElMessage.success('已退出登录')
    },

    async updateProfile(username) {
      try {
        const { user } = await http.put('/api/users/profile', { username })
        this.user = user
        localStorage.setItem('user', JSON.stringify(user))
        ElMessage.success('更新成功')
        return user
      } catch (error) {
        console.error('Update profile error:', error)
        const errorMessage = error.response?.data?.message || '更新失败'
        ElMessage.error(errorMessage)
        throw error
      }
    }
  }
})
